const knex = require("../db"),
    bcrypt = require("bcryptjs"),
    utils = require("../utils");

class AuthService {
    // 注册
    async create(data) {
        try {
            const result = await knex("user").where("username", data.username).first();
            if (!result) {
                await knex("user").insert(data);
            } else {
                throw new Error("账号已存在");
            }
        } catch (error) {
            throw error;
        }
    }
    //登录
    async find({ username, password }) {
        try {
            const result = await knex("user")
                .where({
                    username,
                })
                .first();
            if (!result) {
                throw new Error("账号不存在");
            } else if (!bcrypt.compareSync(utils.decrypt(password) || password, result.password)) {
                throw new Error("密码错误");
            }
        } catch (error) {
            throw error;
        }
    }
}

module.exports = new AuthService();
